package cn.com.wxd.service.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.biz.user.UsersService;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.service.permissions.core.RoleCore;
import cn.com.wxd.service.permissions.entity.FunctionPermissions;
import cn.com.wxd.service.permissions.entity.ModelPermissions;
import cn.com.wxd.service.permissions.entity.PermissionsEntity;
import cn.com.wxd.service.permissions.entity.RoleEntity;
import cn.com.wxd.common.CharUtil;

/**
 * Title:网站用户登录realm
 * Description:自定义的用户登录授权领域
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-7-5 下午5:21:07
 *
 * @author WangXuDong
 * @version 1.0
 */
public class WebsiteRealm extends AuthorizingRealm {

    private static final Logger log = LoggerFactory.getLogger(WebsiteRealm.class);

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }

    private UsersService usersService;

    /**
     * 授权信息（用户授权）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        if (userName != null) {
            AccountInfo accountInfo = usersService.queryAccount(userName);
            UsersInfo user = null;
            if (accountInfo != null) {
                user = accountInfo.getUsersInfo();
            }
            if (user != null) {
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                //根据用户的Roles 查询 角色
                String rolesStr = user.getRoles();
                if(CharUtil.isEmpty(rolesStr)){
                    rolesStr = "";
                }
                String[] roles = rolesStr.split("\2");

                for (String role : roles) {
                    if (CharUtil.isEmpty(role)) {
                        info.addRole(role); //将用户的角色托管给shiro
                        try {
                            RoleEntity roleEntity = RoleCore.getInstance().getRoles(role);
                            if (null != roleEntity) {
                                List<PermissionsEntity> permissionsEntitys = roleEntity.getPermises();
                                if (permissionsEntitys != null) {
                                    for (PermissionsEntity permissionsEntity : permissionsEntitys) {
                                        // 将用户的权限查询到之后托管给shiro
                                        String perm = permissionsEntity.getCode();
                                        List<ModelPermissions> modelPermissionss = permissionsEntity
                                                .getModelPermissions();
                                        if (modelPermissionss != null) {
                                            for (ModelPermissions modelPermissions : modelPermissionss) {
                                                String moperm = perm + ":" + modelPermissions.getCode();
                                                List<FunctionPermissions> functionPermissionss = modelPermissions
                                                        .getFunctionPermissions();
                                                if (functionPermissionss != null) {
                                                    for (FunctionPermissions functionp : functionPermissionss) {
                                                        String funperm = moperm + ":" + functionp.getCode();
                                                        info.addStringPermission(funperm);
                                                    }
                                                }
                                                info.addStringPermission(moperm);
                                            }
                                        }
                                        info.addStringPermission(perm);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error("获取用户的权限错误!", e);
                        }
                    }
                }
                // 在权限里面加入用户的类型
                info.addStringPermission(user.getUserType());
                return info;
            }
        }
        return null;
    }

    /**
     * 用户认证（登录）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String userName = token.getUsername();
        //查询用户之后写入
        if (userName != null && !"".equals(userName)) {
            AccountInfo accountInfo = usersService.queryAccount(userName);
            UsersInfo ui = null;
            if (accountInfo != null) {
                ui = accountInfo.getUsersInfo();
            }
            if (ui != null) {
                //此处无需比对判断密码的正确性,比对的逻辑Shiro会做
                return new SimpleAuthenticationInfo(userName, ui.getPassWord(), ui.getNickName());
            }
        }
        return null;
    }
}
